
from django.db import transaction
from rest_framework import serializers

from goods.models import SKU, GoodsCategory, SPUSpecification, SPU, SpecificationOption, SKUSpecification




class SpecificationSerializer(serializers.Serializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()


class SKUSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True, label='spu名称')
    spu_id = serializers.IntegerField()
    category = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()
    specs = SpecificationSerializer(read_only=True, many=True)

    class Meta:
        model = SKU
        fields = "__all__"

    # 4,重写create方法,数据入库
    @transaction.atomic
    def create(self, validated_data):

        # 0,设置保存点
        sid = transaction.savepoint()

        try:
            sku = SKU.objects.create(**validated_data)
            # 2,获取规格信息,遍历入库

            specs = self.context["request"].data["specs"]
            for spec in specs:
                SKUSpecification.objects.create(sku_id=sku.id, spec_id=spec["spec_id"], option_id=spec["option_id"])
        except Exception as e:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("添加sku失败")
        else:
            # 3,返回响应
            transaction.savepoint_commit(sid)
            return sku
    @transaction.atomic
    def update(self, instance, validated_data):
        # 0,设置保存点
        sid = transaction.savepoint()

        try:
            # 1,修改基础信息
            SKU.objects.filter(id=instance.id).update(**validated_data)

            # 2,删除原有规格
            [spec.delete() for spec in instance.specs.all()]

            # 2,1 修改规格信息
            specs = self.context["request"].data["specs"]
            for spec in specs:
                SKUSpecification.objects.create(sku_id=instance.id, spec_id=spec["spec_id"],
                                                option_id=spec["option_id"])
        except Exception as e:
            transaction.savepoint_rollback(sid)
            raise serializers.ValidationError("更新sku失败")
        else:
            # 3,返回响应
            transaction.savepoint_commit(sid)
            return instance


class SKUCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ["id", "name"]


class SPUListSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ['id', 'name']


# 选项序列化器
class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ["id", "value"]


# 规则序列化器
class SPUSpecificationSerializer(serializers.ModelSerializer):
    options = SpecificationOptionSerializer(read_only=True, many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"



